import * as statusCode from './statusCode'
import { BASEURL } from './config'

const defaultOptions = {
  data: {},
  ignoreToken: false,
  form: false
}

let isModal = false

function request<T = any>(options: RequestOption) {
  let _options = Object.assign(defaultOptions, options)
  let { method, url, data, ignoreToken, form } = _options
  const app = getApp()
  let header: any = {}
  if (form) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  } else {
    header = {
      'content-type': 'application/json'
    }
  }
  if (!ignoreToken) {
    let token = app.globalData.token
    header.Authorization = 'Bearer ' + token
  }

  return new Promise<T>((resolve, reject) => {
    wx.request({
      url: BASEURL + url,
      data,
      header,
      method,
      success: (res => {
        let code = res.statusCode
        if (code === statusCode.SUCCESS) {
          resolve(res.data)
        } else if (code === statusCode.EXPIRE) {
          app.globalData.token = ''
          app.globalData.userInfo = {}
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo');

          // if(!isModal){
          //   console.log("弹窗");
          //   isModal = true
          //   wx.showModal({
          //     title: '提示',
          //     content: '登录过期,是否重新登录?',
          //     success(res) {
          //       isModal = false
          //       if (res.confirm) {
          //         console.log('用户点击确定');
          //         wx.navigateTo({
          //           url: `/pages/login/index`
          //         })
          //       } else if (res.cancel) {
          //         wx.switchTab({
          //           url: '/' + getCurrentPages()[0].route
          //         })
          //       }

          //     }
          //   });
          // }

          reject(res.data)
        } else {
          showToast(`请求错误${url}, CODE: ${code}`)
          reject(res.data)
        }
      }),
      fail: (error) => {
        console.log('%c err', 'color: red;font-weight: bold', error)
        showToast(error.errMsg)
        reject(error)
      }
    })
  })

}

// 封装toast函数
function showToast(title, icon = 'none', duration = 2500, mask = false) {
  wx.showToast({
    title: title || '',
    icon: icon,
    duration,
    mask
  });
}

function get<T = any>(options) {
  return request<T>({
    method: "GET",
    ...options
  })
}

function post<T = any>(options) {
  return new Promise<T>((resolve, reject) => {
    request({
      method: 'POST',
      ...options
    }).then((res: any) => {
      if (res.Code == 0) {
        resolve(res)
      } else {
        wx.showToast({
          title: res.Message ? res.Message : "请求错误"
        })
      }
    })
      .catch(error => {
        reject(error)
      })
  })
}

export {
  request,
  get,
  post
}